package com.yuanqiao.insight.modules.notice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqiao.insight.modules.notice.entity.SysNoticeConfig;
import com.yuanqiao.insight.modules.notice.entity.SysNoticeExtend;
import com.yuanqiao.insight.modules.notice.entity.SysNoticeTemplate;
import com.yuanqiao.insight.modules.notice.mapper.SysNoticeExtendMapper;
import com.yuanqiao.insight.modules.notice.service.ISysNoticeConfigService;
import com.yuanqiao.insight.modules.notice.service.ISysNoticeExtendService;
import com.yuanqiao.insight.modules.notice.service.ISysNoticeTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.AutoLog;
import com.insight.common.system.base.controller.JeecgController;
import com.yuanqiao.insight.acore.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 通知
 * @Author: jeecg-boot
 * @Date: 2021-05-27
 * @Version: V1.0
 */
@Api(tags = "通知")
@RestController
@RequestMapping("/sys/notice/config")
@Slf4j
public class SysNoticeConfigController extends JeecgController<SysNoticeConfig, ISysNoticeConfigService> {
    @Autowired
    private ISysNoticeConfigService sysNoticeConfigService;
    @Autowired
    private SysNoticeExtendMapper sysNoticeExtendMapper;
    @Autowired
    private ISysNoticeExtendService sysNoticeExtendService;
    @Autowired
    private ISysDictService dictService;

    /**
     * 分页列表查询
     *
     * @param sysNoticeConfig
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "通知配置-分页列表查询")
    @ApiOperation(value = "通知-分页列表查询", notes = "通知-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(SysNoticeConfig sysNoticeConfig,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<SysNoticeConfig> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(sysNoticeConfig.getConfigName())) {
            queryWrapper.like("config_name", sysNoticeConfig.getConfigName());
        }
        queryWrapper.eq("delflag", 0);
        queryWrapper.orderByDesc("create_time");
        Page<SysNoticeConfig> page = new Page<SysNoticeConfig>(pageNo, pageSize);
        IPage<SysNoticeConfig> pageList = sysNoticeConfigService.page(page, queryWrapper);
        for (SysNoticeConfig record : pageList.getRecords()) {
            final String noticeType = dictService.queryDictTextByKey("noticeType", record.getConfigType());
            record.setConfigType_dictText(noticeType);
        }
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param sysNoticeConfig
     * @return
     */
    @AutoLog(value = "通知配置-添加")
    @ApiOperation(value = "通知-添加", notes = "通知-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody SysNoticeConfig sysNoticeConfig) {
        sysNoticeConfig.setDelflag(0);

        List<SysNoticeConfig> list = sysNoticeConfigService.list(new QueryWrapper<SysNoticeConfig>().eq("delflag", 0));
        for (SysNoticeConfig sysNoticeConfig1 : list) {
            if (sysNoticeConfig.getConfigName().equals(sysNoticeConfig1.getConfigName())) {
                return Result.error("已经存在的配置！");
            }

        }
        sysNoticeConfigService.save(sysNoticeConfig);
        if (sysNoticeConfig.getExtend() != null) {
            for (SysNoticeExtend sysNoticeExtend : sysNoticeConfig.getExtend()) {
                sysNoticeExtend.setNoticeConfigId(sysNoticeConfig.getId());
            }
            sysNoticeExtendService.saveBatch(sysNoticeConfig.getExtend());
        }

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param sysNoticeConfig
     * @return
     */
    @AutoLog(value = "通知配置-编辑")
    @ApiOperation(value = "通知-编辑", notes = "通知-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody SysNoticeConfig sysNoticeConfig) {
        sysNoticeConfigService.updateById(sysNoticeConfig);
        System.out.println(sysNoticeConfig.getExtend());
        List<SysNoticeExtend> extend = sysNoticeConfig.getExtend();


        if (extend.size() > 0) {
            sysNoticeExtendService.remove(new LambdaQueryWrapper<SysNoticeExtend>().eq(SysNoticeExtend::getNoticeConfigId, sysNoticeConfig.getId()));
            if ("weixin".equals(sysNoticeConfig.getConfigType())) {
                for (SysNoticeExtend sysNoticeExtend : sysNoticeConfig.getExtend()) {
                    sysNoticeExtend.setNoticeConfigId(sysNoticeConfig.getId());
                    sysNoticeExtend.setFieldValue(sysNoticeExtend.getFieldValue());
                    sysNoticeExtendService.save(sysNoticeExtend);
                    break;
                }

            } else {
                for (SysNoticeExtend sysNoticeExtend : sysNoticeConfig.getExtend()) {
                    sysNoticeExtend.setNoticeConfigId(sysNoticeConfig.getId());
                }
                sysNoticeExtendService.saveBatch(sysNoticeConfig.getExtend());
            }


        }


        return Result.OK("编辑成功!");
    }

    @Autowired
    private ISysNoticeTemplateService sysNoticeTemplateService;

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "通知配置-通过id删除")
    @ApiOperation(value = "通知-通过id删除", notes = "通知-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        return deleteById(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "通知配置-批量删除")
    @ApiOperation(value = "通知-批量删除", notes = "通知-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids") String ids) {
        return deleteById(ids);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "通知配置-通过id查询")
    @ApiOperation(value = "通知-通过id查询", notes = "通知-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        SysNoticeConfig sysNoticeConfig = sysNoticeConfigService.getById(id);
        if (sysNoticeConfig == null) {
            return Result.error("未找到对应数据");
        }
        List<SysNoticeExtend> extendAllByConfigId = sysNoticeExtendMapper.findExtendAllByConfigId(id, null);
        sysNoticeConfig.setExtend(extendAllByConfigId);
        return Result.OK(sysNoticeConfig);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sysNoticeConfig
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SysNoticeConfig sysNoticeConfig) {
        return super.exportXls(request, sysNoticeConfig, SysNoticeConfig.class, "通知");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SysNoticeConfig.class);
    }

    /**
     * ### 通知配置-扩展字段
     *
     * @param type           类型
     * @param noticeConfigId 知配置id
     * @return
     */
    @GetMapping("/extend")
    public Result<?> extend(@RequestParam("type") String type, @RequestParam("noticeConfigId") String noticeConfigId) {
        List<SysNoticeExtend> extendAllByConfigId = sysNoticeExtendMapper.findExtendAllByConfigId(noticeConfigId, type);
        return Result.OK(extendAllByConfigId);
    }


    //    @AutoLog(value = "通知-查询全部")
    @ApiOperation(value = "通知-查询全部", notes = "通知-查询全部")
    @GetMapping(value = "/findAll")
    public Result<?> findAll() {
        List<SysNoticeConfig> all = sysNoticeConfigService.list();
        return Result.OK(all);
    }

    private Result<Object> deleteById(String id) {
        final List<String> ids = Arrays.asList(id.split(","));
        int count = sysNoticeTemplateService.count(new LambdaQueryWrapper<SysNoticeTemplate>()
                .in(SysNoticeTemplate::getNoticeConfigId, ids));
        if (count > 0) {
            return Result.error("存在使用此配置的通知模板");
        }
        sysNoticeConfigService.removeByIds(ids);
        sysNoticeExtendService.remove(new LambdaQueryWrapper<SysNoticeExtend>()
                .in(SysNoticeExtend::getNoticeConfigId,ids));
        return Result.OK("删除成功!");
    }

}
